package org.jeecg.modules.syncdata.handler;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.ApiSignUtil;
import org.jeecg.modules.syncdata.entity.SyncLog;
import org.jeecg.modules.syncdata.service.SyncLogService;
import org.jeecg.modules.syncdata.service.SyncService;
import org.jeecg.modules.thirdpartyapi.dto.SyncLogDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.xxl.job.core.biz.model.ReturnT.SUCCESS;

/**
 * 同步处理程序
 *
 * @author zhanglei01
 * @date 2022/03/16
 */
@Slf4j
@Component

public class SyncLogPushHandler  {

    @Autowired
    private SyncLogService syncLogService;

    @Autowired
    private SyncService syncService;

    private static final String API_NAME = "getSyncLog";

    @XxlJob(value = "syncLogPushHandler")
    public ReturnT<String> execute(String jobParam) throws Exception {
        String today = DateUtil.today();
        if (StringUtils.isNotBlank(jobParam)) {
            today = jobParam;
        }
        IPage<SyncLog> syncDataList = syncLogService.getSyncDataList(today, 1);
        int pages = (int) syncDataList.getPages();
        for (int i = 0; i < pages; i++) {
            try {
                syncDataList = syncLogService.getSyncDataList(today, i + 1);
                SyncLogDto syncLogDto = new SyncLogDto();
                syncLogDto.setLogType("sync_log");
                String gzip = ApiSignUtil.gzip(JSONArray.toJSONString(syncDataList.getRecords()));
                syncLogDto.setDataMsg(gzip);
                syncService.callThirdPartyApiUnUpGzip(API_NAME, syncLogDto);
            } catch (Exception e) {
                log.error("调用api:{} 异常", API_NAME, e);
            }
        }
        log.info("推送数据执行完成");
        return SUCCESS;
    }

}
